﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Security.Claims;

namespace Ebusiness_Application.Permission
{
    /// <summary>
    /// 配置自定义鉴权类
    /// </summary>
    public class UserEmaillPermissionValueProvider : PermissionValueProvider
    {
        public UserEmaillPermissionValueProvider(IPermissionStore permissionStore) : base(permissionStore)
        {
        }

        public override string Name => "Email";

        public override async Task<PermissionGrantResult> CheckAsync(PermissionValueCheckContext context)
        {
            //从登录里面获取邮箱
            var Email = context.Principal.FindFirst(AbpClaimTypes.Email)?.Value;
            if (Email == null)
            {
                return PermissionGrantResult.Undefined;
            }

            //从权限表查询是否有权限
            return await PermissionStore.IsGrantedAsync(context.Permission.Name, Name, Email) ? PermissionGrantResult.Granted : PermissionGrantResult.Undefined;
        }

        /// <summary>
        /// 多权限鉴权方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public override async Task<MultiplePermissionGrantResult> CheckAsync(PermissionValuesCheckContext context)
        {
            var PermissionsNames = context.Permissions.Select(x => x.Name).Distinct().ToArray();
            Check.NotNullOrEmpty(PermissionsNames, nameof(PermissionsNames));

            var Email = context.Principal.FindFirst(AbpClaimTypes.Email)?.Value;
            if (Email == null)
            {
                //授权失败
                return new MultiplePermissionGrantResult(PermissionsNames);
            }
            return await PermissionStore.IsGrantedAsync(PermissionsNames, Name, Email);
        }
    }
}
